using Flurl.Http;
using Newtonsoft.Json;
using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.Service.Cache;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Pay.Service {
    public class LogisticsDetailsService : ServiceBase, ILogisticsDetailsService, IDisposable {
        private IUnitOfWork _iUnitOfWork;

        public LogisticsDetailsService(IUnitOfWork iUnitOfWork) : base(iUnitOfWork) {
            _iUnitOfWork = iUnitOfWork;
        }

        /// <summary>
        /// 新增物流信息
        /// </summary>
        /// <param name="dto"></param>
        public int Add(logistics_details_dto dto) {
            LogisticsDetails model = new LogisticsDetails();
            dto.ToDtoObject<LogisticsDetails>(model);
            context.LogisticsDetails.Add(model);
            int result = _iUnitOfWork.Commit("LogisticsDetails" + dto.logistics.parentid);
            dto.id = model.Id;
            return result;
        }
        ///<summary>
        ///电商Sign签名
        ///</summary>
        ///<param name="content">内容</param>
        ///<param name="keyValue">Appkey</param>
        ///<param name="charset">URL编码 </param>
        ///<returns>DataSign签名</returns>
        private string encrypt(String content, String keyValue, String charset) {
            if (keyValue != null) {
                return base64(MD5(content + keyValue, charset), charset);
            }
            return base64(MD5(content, charset), charset);
        }
        ///<summary>
        /// 字符串MD5加密
        ///</summary>
        ///<param name="str">要加密的字符串</param>
        ///<param name="charset">编码方式</param>
        ///<returns>密文</returns>
        private string MD5(string str, string charset) {
            byte[] buffer = System.Text.Encoding.GetEncoding(charset).GetBytes(str);
            try {
                MD5CryptoServiceProvider check;
                check = new MD5CryptoServiceProvider();
                byte[] somme = check.ComputeHash(buffer);
                string ret = "";
                foreach (byte a in somme) {
                    if (a < 16)
                        ret += "0" + a.ToString("X");
                    else
                        ret += a.ToString("X");
                }
                return ret.ToLower();
            } catch {
                throw;
            }
        }

        /// <summary>
        /// base64编码
        /// </summary>
        /// <param name="str">内容</param>
        /// <param name="charset">编码方式</param>
        /// <returns></returns>
        private string base64(String str, String charset) {
            return Convert.ToBase64String(System.Text.Encoding.GetEncoding(charset).GetBytes(str));
        }
        private string sendPost(string url, Dictionary<string, string> param) {
            string result = "";
            StringBuilder postData = new StringBuilder();
            if (param != null && param.Count > 0) {
                foreach (var p in param) {
                    if (postData.Length > 0) {
                        postData.Append("&");
                    }
                    postData.Append(p.Key);
                    postData.Append("=");
                    postData.Append(p.Value);
                }
            }
            byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(postData.ToString());
            try {

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.ContentType = "application/x-www-form-urlencoded";
                request.Referer = url;
                request.Accept = "*/*";
                request.Timeout = 30 * 1000;
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
                request.Method = "POST";
                request.ContentLength = byteData.Length;
                Stream stream = request.GetRequestStream();
                stream.Write(byteData, 0, byteData.Length);
                stream.Flush();
                stream.Close();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream backStream = response.GetResponseStream();
                StreamReader sr = new StreamReader(backStream, Encoding.GetEncoding("UTF-8"));
                result = sr.ReadToEnd();
                sr.Close();
                backStream.Close();
                response.Close();
                request.Abort();
            } catch (Exception ex) {
                result = ex.Message;
            }
            return result;
        }
        /// <summary>
        /// 获取物流详情列表
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public logistic_results GetList(order_dto order) {
            Dictionary<string, string> dics = new Dictionary<string, string>();
            var requestData = new { OrderCode = "", ShipperCode = order.shipping.express_no, LogisticCode = order.shipping.ship_order_number }.ToJson();
            dics.Add("RequestData", HttpUtility.UrlEncode(requestData, Encoding.UTF8));
            dics.Add("EBusinessID", RequestMethod.express_appid);
            dics.Add("RequestType", "8001");

            string dataSign = LogisticHelper.encrypt(requestData, RequestMethod.express_appkey);
            dics.Add("DataSign", HttpUtility.UrlEncode(dataSign, Encoding.UTF8));
            dics.Add("DataType", "2");

            var list = new List<logistics_details_dto>();
            var models = context.logisticsLists.Where(x => x.Id == order.pay_info.plateid).FirstOrDefault();
            if (models != null && models.ParentId != null) {
                list = context.LogisticsDetails.Where(x => x.LogisticsId == order.pay_info.plateid || x.LogisticsId == models.ParentId).OrderBy(x => x.LogisticsTime).FromCache<LogisticsDetails, logistics_details_dto>("LogisticsDetails" + order.id);
            } else {
                list = context.LogisticsDetails.Where(x => x.LogisticsId == order.pay_info.plateid).FromCache<LogisticsDetails, logistics_details_dto>("LogisticsDetails" + order.id);
            }
            logistic_results model = null;

            try {
                //model = JsonConvert.DeserializeObject<logistic_results>(sendPost(RequestMethod.express_url, dics));
                model = (RequestMethod.express_url).PostUrlEncodedAsync(dics).ReceiveJson<logistic_results>().Result;

            } catch (Exception ex) {
                if (ex is FlurlHttpException) {
                    var error = (ex as FlurlHttpException).GetResponseJsonAsync<easemob_error>().Result;
                    var log = IocHelper.Get<ILogHelper>("ui_error");
                    log.Error(error.error + ":" + error.error_description);
                }
                model = new logistic_results();
            }
            if (model == null) {
                model.Success = true;
                model.State = "2";
            }
            var traces = new List<Trace>();
            if (list != null && list.Count > 0) {
                foreach (var item in list) {
                    var trace = new Trace();
                    trace.AcceptStation = EnumExtensions.ToDescription(item.logisticsstatus);
                    trace.AcceptTime = item.logisticstime.ToString("yyyy-MM-dd hh:mm:ss");
                    model.Traces.Add(trace);
                }
            }
            return model;
        }
        /// <summary>
        /// 根据订单id获取物流信息
        /// </summary>
        /// <param name="order_id"></param>
        /// <returns></returns>
        public async Task<logistic_results> GetLogisticInfo(order_dto order) {
            Dictionary<string, string> dics = new Dictionary<string, string>();
            var requestData = new {
                OrderCode = "",
                ShipperCode = StringHelper.ReplaceExpressCode(order.shipping.express_no),
                LogisticCode = order.shipping.ship_order_number
            }.ToJson();
            dics.Add("RequestData", HttpUtility.UrlEncode(requestData, Encoding.UTF8));
            dics.Add("EBusinessID", RequestMethod.express_appid);
            dics.Add("RequestType", "8001");
            string dataSign = LogisticHelper.encrypt(requestData, RequestMethod.express_appkey);
            dics.Add("DataSign", HttpUtility.UrlEncode(dataSign, Encoding.UTF8));
            dics.Add("DataType", "2");

            var model = new logistic_results();
            try {
                model = await (RequestMethod.express_url).PostUrlEncodedAsync(dics).ReceiveJson<logistic_results>();
            } catch (Exception ex) {
                if (ex is FlurlHttpException) {
                    var error = (ex as FlurlHttpException).GetResponseJsonAsync<easemob_error>().Result;
                    var log = IocHelper.Get<ILogHelper>("ui_error");
                    log.Error(error.error + ":" + error.error_description);
                }
            }
            return model;
        }
        /// <summary>
        /// 订单 快递100 物流
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public k100_logistic_results GetK100List(order_dto order) {
            string url = RequestMethod.k100_express_url;
            Encoding encoding = Encoding.GetEncoding("utf-8");
            //参数
            String param = "{\"com\":\"" + order.shipping.express_no.ToLower() + "\",\"num\":\"" + order.shipping.ship_order_number + "\",\"from\":\"\",\"to\":\"\"}";
            String customer = RequestMethod.k100_customer;
            String key = RequestMethod.k100_key;
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] InBytes = Encoding.GetEncoding("UTF-8").GetBytes(param + key + customer);
            byte[] OutBytes = md5.ComputeHash(InBytes);
            string OutString = "";
            for (int i = 0; i < OutBytes.Length; i++) {
                OutString += OutBytes[i].ToString("x2");
            }
            String sign = OutString.ToUpper();
            Dictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("param", param);
            parameters.Add("customer", customer);
            parameters.Add("sign", sign);
            k100_logistic_results model = null;
            try {
                model = JsonConvert.DeserializeObject<k100_logistic_results>(sendPost(url, parameters));


            } catch (Exception ex) {
                if (ex is FlurlHttpException) {
                    var error = (ex as FlurlHttpException).GetResponseJsonAsync<easemob_error>().Result;
                    var log = IocHelper.Get<ILogHelper>("ui_error");
                    log.Error(error.error + ":" + error.error_description);
                }
                model = new k100_logistic_results();
            }
            return model;
        }
        /// <summary>
        /// 获取国外物流状态
        /// </summary>
        /// <param name="order_id"></param>
        /// <returns></returns>
        public List<logistics_details_dto> GetDeteil(long order_id) {
            var order = context.Orders.FirstOrDefault(c => c.Id == order_id).ToDtoObject<order_dto>();
            var models = context.logisticsLists.Where(x => x.Id == order.pay_info.plateid).FirstOrDefault();
            List<logistics_details_dto> list = new List<logistics_details_dto>();
            if (models != null && models.ParentId != null) {
                list = context.LogisticsDetails.Where(x => x.LogisticsId == order.pay_info.plateid || x.LogisticsId == models.ParentId).OrderBy(x => x.LogisticsTime).FromCache<LogisticsDetails, logistics_details_dto>("LogisticsDetails" + order_id);
            } else {
                list = context.LogisticsDetails.Where(x => x.LogisticsId == order.pay_info.plateid).FromCache<LogisticsDetails, logistics_details_dto>("LogisticsDetails" + order_id);
            }
            return list;
        }

        /// <summary>
        /// 通过物流id获取国外物流
        /// </summary>
        /// <param name="logistics"></param>
        /// <returns></returns>
        public List<logistics_details_dto> GetLogisticsDeteil(List<logistics_list_dto> logistics) {
            var logistic = logistics.Select(c => c.id).ToArray();
            var logistics_details = context.LogisticsDetails.Where(c => logistic.Contains(c.LogisticsId)).ToList().ToDtoList<logistics_details_dto>();
            return logistics_details;
        }
        public logistics_details_dto GetLogistics(long LogisticId, LogisticsStatuss statuss) {
            return context.LogisticsDetails.Where(x => x.LogisticsId == LogisticId && x.LogisticsStatus == statuss).FromCacheFirstOrDefault<LogisticsDetails, logistics_details_dto>();
        }

    }
}
